package com.xique.blelock.view.AcountManager;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.SearchView;

import com.alibaba.fastjson.JSON;
import com.clj.fastble.utils.HexUtil;
import com.ivin.crop.Log;
import com.xique.blelock.Adapter.UserAdapter;
import com.xique.blelock.Adapter.UserNetAdapter;
import com.xique.blelock.Interface.OnItemClickListener;
import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.BleUtils;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.UserNetInfo;
import com.xique.blelock.model.UserOfLockinfo;
import com.xique.blelock.view.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/12/11.
 */

public class AddUserActitivy extends BaseActivity {


    @BindView(R.id.searchbtn)
    Button searchBtn;

    @BindView(R.id.searchView)
    SearchView mSearchView;

    @BindView(R.id.RecyclerView)
    RecyclerView recyclerView;

    private UserNetAdapter userNetAdapter;

    private List<UserNetInfo>  userNetInfoList = new ArrayList<>();

    private List<UserOfLockinfo> userOfLockinfos ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.adduserlayout);
        ButterKnife.bind(this);
        initView();

    }


    @Override
    protected void initView() {
        super.initView();
        userOfLockinfos = getIntent().getParcelableArrayListExtra(Stringkey.USER_LIST);

        mSearchView.setOnQueryTextListener(ListenQuery);
        mSearchView.setIconified(false);
        mSearchView.setIconifiedByDefault(false);


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        userNetAdapter = new UserNetAdapter(userNetInfoList);

        recyclerView.setAdapter(userNetAdapter);
        initListen();

    }

    private void initListen() {
        userNetAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(Object object, int position) {
                UserNetInfo userNetInfo = (UserNetInfo) object;
                AddUser2Lock(userNetInfo);

            }
        });
    }

    //添加用户到设备下，那么他就有管理开锁权限
    private void AddUser2Lock(UserNetInfo userNetInfo) {
        mSearchView.clearFocus();
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("bandUid", userNetInfo.getUid());//E0:4C:63:6D:82:43
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));
            jsonobject.put("role", 2);
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.addBandUser(jsonobject.toString()).enqueue(new Callback<NetResult>() {
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {

                Log.e("查询到用户:"+ JSON.toJSONString(response.body()), "");
                if(response.body()!= null && response.body().isSuccess()){
                        showToast(AddUserActitivy.this, "添加成功");
                    userNetInfoList.get(0).setSet(true);
                    userNetAdapter.notifyDataSetChanged();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }, 300);

                }else {
                    showToast(AddUserActitivy.this, response.body().getMessage());
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }


    private SearchView.OnQueryTextListener ListenQuery = new SearchView.OnQueryTextListener() {

        // 当点击搜索按钮时触发该方法
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public boolean onQueryTextSubmit(String name) {

//            showSearchResult(name);
            return false;
        }

        // 当搜索内容改变时触发该方法

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public boolean onQueryTextChange(final String name) {
//            showSearchResult(name);

            return false;
        }
    };

    @OnClick(R.id.searchbtn)
    public  void OnclickSearch(){
//        user/queryUserInfoByPhone
        //清除焦点，收软键盘
        if(mSearchView.getQuery().length() != 11){
            showToast(this, "请输入正确手机号");
            return;
        }
        mSearchView.clearFocus();
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("phone", mSearchView.getQuery().toString());//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.getUserByPhone(jsonobject.toString()).enqueue(new Callback<NetResult<UserNetInfo>>() {
            @Override
            public void onResponse(Call<NetResult<UserNetInfo>> call, Response<NetResult<UserNetInfo>> response) {

                Log.e("查询到用户:"+ JSON.toJSONString(response.body()), "");
                if(response.body()!= null && response.body().isSuccess()){

                    UserNetInfo userNetInfo = response.body().getData();
                    if(userNetInfo != null){
                        if(!userNetInfoList.contains(userNetInfo)){
                            UserOfLockinfo userOfLockinfo = new UserOfLockinfo();
                            userOfLockinfo.setUid(userNetInfo.getUid());
                            if(userOfLockinfos.contains( userOfLockinfo)){
                                userNetInfo.setSet(true);
                            }


                            userNetInfoList.add(userNetInfo);
                            userNetAdapter.setDeviceList(userNetInfoList);
                            userNetAdapter.notifyDataSetChanged();
                        }

                    }
                }else {
                    showToast(AddUserActitivy.this, "没有查到到用户");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult<UserNetInfo>> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }

    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }
}
